<?php


class SellerCoupon extends IController implements sellerAuthorization
{
    public $layout = 'seller';

    /**
     *
     * 优惠券列表
     *
     */
    public function coupon_list()
    {
        $seller_id   = $this->seller['seller_id'];
        $where       = "seller_id='$seller_id'";
        $page        = IReq::get('page') ? IFilter::act(IReq::get('page'), 'int') : 1;
        $coupon_name = IFilter::act(IReq::get('coupon_name'));
        if ($coupon_name) {
            $where .= " and name like '$coupon_name%' ";
        }
        $couponHandle         = new IQuery('coupon_groups');
        $couponHandle->order  = "create_time desc";
        $couponHandle->fields = "*";
        $couponHandle->where  = $where;
        $couponHandle->page   = $page;
        $this->couponHandle   = $couponHandle;
        $couponData           = $this->couponHandle->find();
        $data                 = array();
        $data['coupon_name']  = $coupon_name;
        if ($couponData) {
            $couponArr = array();
            foreach ($couponData as $val) {
                $couponArr[] = $val['id'];
            }
            $couponIds = trim(join(',', $couponArr), ',');
            $couponDb  = new IModel("coupon");
            //总数量
            /*       $sumResult = $couponDb->query("coupon_group_id in ({$couponIds})  and status in(1,2,3,4)  group by coupon_group_id  ", 'count(*) as count,coupon_group_id');
                   $sumData   = array();
                   if ($sumResult) {
                       foreach ($sumResult as $sum_val) {
                           $sumData[$sum_val['coupon_group_id']] = $sum_val;
                       }
                   }*/
            //未发放
            $unSendResult = $couponDb->query("coupon_group_id in ({$couponIds})   and status =1 group by coupon_group_id  ", 'count(*) as count,coupon_group_id');

            $unSendData = array();
            if ($unSendResult) {
                foreach ($unSendResult as $unSend_val) {
                    $unSendData[$unSend_val['coupon_group_id']] = $unSend_val;
                }
            }
            //未使用
            $unUseResult = $couponDb->query("coupon_group_id in ({$couponIds})   and status =2 group by coupon_group_id  ", 'count(*) as count,coupon_group_id');

            $unUseData = array();
            if ($unUseResult) {
                foreach ($unUseResult as $un_val) {
                    $unUseData[$un_val['coupon_group_id']] = $un_val;
                }
            }
            //已经使用
            $hasUseResult = $couponDb->query("coupon_group_id in ({$couponIds})   and status =3 group by coupon_group_id  ", 'count(*) as count,coupon_group_id');
            $hasUseData   = array();
            if ($hasUseResult) {
                foreach ($hasUseResult as $has_val) {
                    $hasUseData[$has_val['coupon_group_id']] = $has_val;
                }
            }
            //已经过期
            $outDateResult = $couponDb->query("coupon_group_id in ({$couponIds})  and status in(4,5,6)  group by coupon_group_id  ", 'count(*) as count,coupon_group_id');
            $outData       = array();
            if ($outDateResult) {
                foreach ($outDateResult as $out_val) {
                    $outData[$out_val['coupon_group_id']] = $out_val;
                }
            }
            $data['un_send'] = $unSendData;
            // $data['sum']      = $sumData;
            $data['un_use']   = $unUseData;
            $data['has_use']  = $hasUseData;
            $data['out_data'] = $outData;

        }
        $this->setRenderData($data);
        $this->redirect('coupon_list');
    }

    /**
     *
     * 查看优惠券配置
     *
     */
    public function rule_config()
    {
        $seller_id        = $this->seller['seller_id'];
        $couponRuleDb     = new IModel('coupon_rule');
        $ruleInfo['info'] = $couponRuleDb->getObj('seller_id=' . $seller_id);
        $this->setRenderData($ruleInfo);
        $this->redirect('rule_config');
    }

    /**
     *
     * 编辑优惠券配置
     *
     */
    public function rule_config_save()
    {
        $seller_id = $this->seller['seller_id'];
        $type      = IFilter::act(IReq::get('type'), 'int');
        if ($seller_id) {
            $ruleData     = array(
                'type' => $type,
            );
            $couponRuleDb = new IModel('coupon_rule');
            $ruleInfo     = $couponRuleDb->getObj('seller_id=' . $seller_id);
            if ($ruleInfo) {
                $ruleData['update_time'] = ITime::getDateTime();
                $couponRuleDb->setData($ruleData);
                $where = "seller_id=" . $seller_id;
                $couponRuleDb->update($where);
            } else {
                $ruleData['create_time'] = ITime::getDateTime();
                $ruleData['seller_id']   = $seller_id;
                $couponRuleDb->setData($ruleData);
                $couponRuleDb->add();
            }
        }
        $this->redirect('rule_config');

    }

    /**
     * 添加优惠券页面
     *
     */
    public function create_coupon()
    {
        $this->redirect('create_coupon');
    }

    /**
     * 创建保存优惠券
     *
     */
    public function save_coupon()
    {
        //检查表单提交状态
        if (!$_POST) {
            die('请确认表单提交正确');
        }
        $use_channels   = IFilter::act(IReq::get('use_channels'), 'int');
        $type           = IFilter::act(IReq::get('type'), 'int');
        $use_type       = IFilter::act(IReq::get('use_type'), 'int');
        $name           = IFilter::act(IReq::get('name'), 'txt');
        $goods_id       = IFilter::act(IReq::get('goods_id'));
        $discount_money = IFilter::act(IReq::get('discount_money'), 'float');
        $discount_point = IFilter::act(IReq::get('discount_point'), 'int');
        $condition      = IFilter::act(IReq::get('condition'), 'int');
        $full_money     = IFilter::act(IReq::get('full_money'), 'float');
        $full_point     = IFilter::act(IReq::get('full_point'), 'int');
        $start_time     = IFilter::act(IReq::get('start_time'));
        $end_time       = IFilter::act(IReq::get('end_time'));
        $description    = IFilter::act(IReq::get('description'), 'txt');
        $goods_sale     = IFilter::act(IReq::get('goods_sale'), 'int');
        $goods_sale_num = IFilter::act(IReq::get('goods_sale_num'), 'int') ? IFilter::act(IReq::get('goods_sale_num'), 'int') : 0;
        $prop_sale      = IFilter::act(IReq::get('prop_sale'), 'int');
        $image1         = IFilter::act(IReq::get('image1'));
        $image2         = IFilter::act(IReq::get('image2'));
        $seller_id      = $this->seller['seller_id'];
        $couponData     = array(
            'use_channels'       => $use_channels,
            'use_type'           => $use_type,
            'type'               => $type,
            'name'               => $name,
            'discount_money'     => $discount_money,
            'discount_point'     => $discount_point,
            'condition'          => $condition,
            'start_time'         => $start_time,
            'end_time'           => $end_time . " 23:59:59",
            'description'        => $description,
            'goods_sale'         => $goods_sale,
            'prop_sale'          => $prop_sale,
            'seller_id'          => $seller_id,
            'restrict_seller_id' => $seller_id,
            'status'             => 1,
            'create_time'        => ITime::getDateTime(),
        );
        if ($condition == 2) {
            $couponData['full_money'] = $full_money;
            $couponData['full_point'] = $full_point;
        }
        if ($goods_sale == 1) {
            $couponData['goods_sale_num'] = $goods_sale_num;
        }
        if ($prop_sale == 1) {
            $couponData['image1'] = $image1 ? $image1 : '';
            $couponData['image2'] = $image2 ? $image2 : '';
        }
        $couponDb = new IModel('coupon_groups');
        $couponDb->setData($couponData);
        $couponGroupId = $couponDb->add();
        if ($couponGroupId === false) {
            $couponDb->rollback();
            die("创建优惠出错，主表数据写入失败！");
        }
        //加入优惠券缓存列表 用来做检测优惠券过期 消息提醒数据源
        $redisObj = new IRedisCache();
        //获取redis实例
        $cache = $redisObj->r('shop');
        //获取redis配置的key
        $key = $redisObj->redis_key('coupon_list');
        $cache->zAdd($key, strtotime($couponData['end_time']), $couponGroupId);
        if ($goods_id) {
            $goodsCouponDb = new IModel('goods_coupon');
            foreach (array_unique($goods_id) as $value) {
                $goodsCouponData = array(
                    'coupon_group_id' => $couponGroupId,
                    'goods_id'        => $value
                );
                $goodsCouponDb->setData($goodsCouponData);
                $goodsCouponId = $goodsCouponDb->add();
                if ($goodsCouponId === false) {
                    $goodsCouponDb->rollback();
                    die("创建优惠出错，商品优惠券表写入失败！");
                }
            }
        }
        //加入道具
        if ($couponGroupId && $prop_sale == 1) {
            $zxlObj            = new  zxlhelper();
            $propData          = array(
                'name'            => $name,
                'expire_from'     => date('Ymd', strtotime($start_time)),
                'expire_to'       => date('Ymd', strtotime($end_time)),
                'remark'          => $description,
                'small_image_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/' . $image1,
                'large_image_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/' . $image2,
            );
            $seller_name       = $this->seller['tenant_id'];
            $tenantTokenResult = SystemToken::getTenantTokenList(array($seller_name));
            $token             = $tenantTokenResult['success'][$seller_name];
            if ($tenantTokenResult['failure']) {
                die("创建优惠出错，优惠券加入道具失败,租户获取Token失败！");
            }
            $propData['token'] = rawurldecode($token);
            $addPropResult     = $zxlObj->couponAddProps($propData);
            if ($addPropResult !== false && $addPropResult['coupon_props_id'] > 0) {
                $couponPropsData = array(
                    'props_id'        => $addPropResult['coupon_props_id'],
                    'seller_id'       => $seller_id,
                    'coupon_group_id' => $couponGroupId
                );
                $couponPropsDb   = new IModel('coupon_props');
                $couponPropsDb->setData($couponPropsData);
                $couponPropsDb->add();
            } else {
                die("创建优惠出错，优惠券加入道具失败！");
            }
        }
        //加入到商品销售
        if ($couponGroupId && $goods_sale == 1) {
            //推入队列生成优惠券
            $mqData = array(
                'coupon_group_id' => $couponGroupId,
                'create_time'     => $couponData['create_time'],
                'goods_sale_num'  => $goods_sale_num,
                'use_type'        => $use_type,
            );
            $this->pushCouponMq($mqData);
            //变更日志记录
            $couponUpdateLogDb   = new IModel('coupon_update_log');
            $couponUpdateLogData = array(
                'coupon_group_id' => $couponGroupId,
                'change_sum'      => $goods_sale_num,
                'create_time'     => ITime::getDateTime()
            );
            $couponUpdateLogDb->setData($couponUpdateLogData);
            $couponUpdateLogDb->add();

            $goodsData = array(
                'name'            => $name,
                'store_nums'      => $goods_sale_num,
                'market_price'    => $discount_money,
                'coupon_group_id' => $couponGroupId,
            );
            if ($image2) {
                $goodsData['img'] = $image2;
            }

            $this->joinGoodSell($goodsData);
        }
        $this->redirect('coupon_list');
    }

    /**
     * 推入队列生成优惠券
     *
     * @param $data
     *
     * @return array|string
     */
    public function pushCouponMq($data)
    {
        if (empty($data)) {
            return array();
        }
        $couponDetailData = array();
        //当成商品发放
        if ($data['goods_sale_num']) {
            $couponObj = new coupon();
            for ($i = 0; $i < $data['goods_sale_num']; $i++) {
                $couponDetailData[] = json_encode(array(
                    'coupon_group_id' => $data['coupon_group_id'],
                    'code'            => $couponObj->getUniqueCode(16),
                    'send_type'       => 1,
                    'create_time'     => $data['create_time'],
                    'use_type'        => $data['use_type'],
                ));
            }
        }
        $redis_obj = new redisMq();

        return $redis_obj->multiplePush(array('handel_coupon_queue' => $couponDetailData));
    }

    /**
     * 加入到商品销售
     *
     * @param $data
     *
     * @return bool
     */
    public function joinGoodSell($data)
    {
        if (empty($data)) {
            return false;
        }
        $goodsData['name']            = $data['name'];
        $goodsData['seller_id']       = $this->seller['seller_id'];
        $goodsData['goods_no']        = goods_class::createGoodsNo();
        $goodsData['store_nums']      = $data['store_nums'];
        $goodsData['img']             = trim($data['img'],"/");
        $goodsData['coupon_group_id'] = $data['coupon_group_id'];
        $goodsData['market_price']    = $data['market_price'];
        $goodsData['create_time']     = ITime::getDateTime();
        $goodsData['create_time']     = ITime::getDateTime();
        $goodsData['type']            = 2;
        $goodsData['is_del']          = 3;
        //处理商品
        $goodsDB = new IModel('goods');
        $goodsDB->setData($goodsData);
        $id = $goodsDB->add();
        //处理商品图片
        $photoRelationDB = new IModel('goods_photo_relation');
        $photoDB         = new IModel('goods_photo');
        $photoData       = $photoDB->getObj("img='{$goodsData['img']}'");
        if ($photoData) {
            $photoRelationDB->setData(array(
                'goods_id' => $id,
                'photo_id' => $photoData['id']
            ));
            $photoRelationDB->add();
        }

        return $id;
    }

    /**
     * 编辑查看优惠券
     *
     */
    public function coupon_edit()
    {
        $coupon_id = IFilter::act(IReq::get('id'), 'int');
        if (empty($coupon_id)) {
            die("编辑优惠券出错啦!");
        }
        $couponGroupsDb = new IModel('coupon_groups');
        $coupon_info    = $couponGroupsDb->getObj("id=" . $coupon_id);
        if (empty($coupon_info)) {
            die("查询不到优惠券信息!");
        }
        $goodsCouponDb    = new IModel('goods_coupon');
        $couponGoodResult = $goodsCouponDb->query("coupon_group_id=" . $coupon_info['id']);
        $goodsInfo        = array();
        if ($couponGoodResult) {
            $goodsIds = array();
            foreach ($couponGoodResult as $value) {
                $goodsIds[] = $value['goods_id'];
            }
            $goodsIdStr = join(",", $goodsIds);
            $goodsDb    = new IModel('goods');
            $goodsInfo  = $goodsDb->query("id in($goodsIdStr)", 'name,spec_array,sell_price,store_nums,final_point,final_price');
        }
        if ($coupon_info['goods_sale'] == 1) {
            $couponDb        = new IModel('coupon');
            $couponSumResult = $couponDb->query("send_type =1 and status in(1,2,3,4,5,6) and coupon_group_id=" . $coupon_info['id'] . "  GROUP BY status ", ' status,count(*) as count');
            $goods_sale_num  = 0;
            $numArr          = array();
            if ($couponSumResult) {
                foreach ($couponSumResult as $val) {
                    $goods_sale_num         += $val['count'];
                    $numArr[$val['status']] = $val['count'];
                }
            }
            $coupon_info['has_send'] = $numArr[2] + $numArr[3];
            $coupon_info['remain']   = $coupon_info['goods_sale_num'] - $coupon_info['has_send'] - $numArr[4];
            $coupon_info['out_date'] = $numArr[4] + $numArr[5] + $numArr[6];


        }
        $data['goods_info'] = $goodsInfo;
        $data['info']       = $coupon_info;
        $this->setRenderData($data);
        $this->redirect('coupon_edit');
    }

    /**
     *
     * 优惠券编辑保存
     *
     */
    public function coupon_update()
    {
        $coupon_id = IFilter::act(IReq::get('coupon_id'), 'int');
        if (empty($coupon_id)) {
            die("编辑优惠券出错啦!");
        }
        $seller_id      = $this->seller['seller_id'];
        $couponGroupsDb = new IModel('coupon_groups');
        $description    = IFilter::act(IReq::get('description'), 'txt');
        $goods_sale     = IFilter::act(IReq::get('goods_sale'), 'int');
        $goods_sale_num = IFilter::act(IReq::get('goods_sale_num'), 'int') ? IFilter::act(IReq::get('goods_sale_num'), 'int') : 0;
        $prop_sale      = IFilter::act(IReq::get('prop_sale'), 'int');
        $image1         = IFilter::act(IReq::get('image1'));
        $image2         = IFilter::act(IReq::get('image2'));
        if ($goods_sale) {
            $couponGroupsData['goods_sale'] = $goods_sale;
        }
        $couponGroupsData['image1'] = $image1;
        $couponGroupsData['image2'] = $image2;
        if ($prop_sale) {
            $couponGroupsData['prop_sale'] = $prop_sale;
        }

        $discount_money = IFilter::act(IReq::get('discount_money'), 'float');
        $name           = IFilter::act(IReq::get('coupon_name'), 'txt');

        $couponGroupsData['update_time'] = ITime::getDateTime();
        $couponGroupsData['description'] = $description;

        $couponGroupsDb->setData($couponGroupsData);
        $where            = "id=" . $coupon_id;
        $updateRes        = $couponGroupsDb->update($where);
        $couponGroupsInfo = $couponGroupsDb->getObj($where);
        if ($updateRes && $goods_sale == 1) {
            //推入队列生成优惠券
            $mqData = array(
                'coupon_group_id' => $coupon_id,
                'create_time'     => ITime::getDateTime(),
                'goods_sale_num'  => $goods_sale_num,
                'use_type'        => $couponGroupsInfo['use_type'],
            );
            $this->pushCouponMq($mqData);
            //变更日志记录
            $couponUpdateLogDb   = new IModel('coupon_update_log');
            $couponUpdateLogData = array(
                'coupon_group_id' => $coupon_id,
                'change_sum'      => $goods_sale_num,
                'create_time'     => ITime::getDateTime()
            );
            $couponUpdateLogDb->setData($couponUpdateLogData);
            $couponUpdateLogDb->add();
            $goodsData = array(
                'name'            => $name,
                'store_nums'      => $goods_sale_num,
                'market_price'    => $discount_money,
                'coupon_group_id' => $coupon_id,
            );
            if ($image2) {
                $goodsData['img'] = $image2;
            }
            $this->joinGoodSell($goodsData);
        }
        $small_image_url = 'https://' . $_SERVER['HTTP_HOST'] . '/' . $image1;
        $large_image_url = 'https://' . $_SERVER['HTTP_HOST'] . '/' . $image2;
        $seller_name     = $this->seller['tenant_id'];
        if ($updateRes && $couponGroupsData['prop_sale'] == 1) {
            $zxlObj            = new  zxlhelper();
            $propData          = array(
                'name'            => $name,
                'expire_from'     => date('Ymd', strtotime($couponGroupsInfo['start_time'])),
                'expire_to'       => date('Ymd', strtotime($couponGroupsInfo['end_time'])),
                'remark'          => $description,
                'small_image_url' => $small_image_url,
                'large_image_url' => $large_image_url,
            );
            $tenantTokenResult = SystemToken::getTenantTokenList(array($seller_name));
            $token             = $tenantTokenResult['success'][$seller_name];
            if ($tenantTokenResult['failure']) {
                die("创建优惠出错，优惠券加入道具失败,租户获取Token失败！");
            }
            $propData['token'] = rawurldecode($token);
            $addPropResult     = $zxlObj->couponAddProps($propData);
            if ($addPropResult !== false && $addPropResult['coupon_props_id'] > 0) {
                $couponPropsData = array(
                    'props_id'        => $addPropResult['coupon_props_id'],
                    'seller_id'       => $seller_id,
                    'coupon_group_id' => $coupon_id
                );
                $couponPropsDb   = new IModel('coupon_props');
                $couponPropsDb->setData($couponPropsData);
                $couponPropsDb->add();
            } else {
                $couponGroupsDb->rollback();
            }
        }
        if ($updateRes) {
            $couponPropsDb  = new IModel('coupon_props');
            $couponPropsRes = $couponPropsDb->getObj("coupon_group_id=$coupon_id");
            if ($couponPropsRes) {
                $tenantTokenResult = SystemToken::getTenantTokenList(array($seller_name));
                $token             = $tenantTokenResult['success'][$seller_name];
                if ($tenantTokenResult['failure']) {
                    die("编辑时优惠券 ，同步道具租户获取Token失败!");
                }
                $propData = array(
                    'coupon_props_id' => $couponPropsRes['props_id'],
                    'remark'          => $description,
                    'small_image_url' => $small_image_url,
                    'large_image_url' => $large_image_url,
                    'token'           => rawurldecode($token)
                );
                $zxlObj   = new  zxlhelper();
                $res      = $zxlObj->couponUpdateProps($propData);
                if ($res === false) {
                    $couponGroupsDb->rollback();
                    die("编辑优惠券,同步到道具出错啦!");
                }
            }
        }

        $this->redirect('coupon_list');
    }

    /**
     * 编辑数量页面
     *
     */
    public function update_num()
    {
        $this->layout = '';
        $coupon_id    = IFilter::act(IReq::get('coupon_id'), 'int');
        $use_type     = IFilter::act(IReq::get('use_type'), 'int');
        if (empty($coupon_id)) {
            die("编辑优惠券数量出错了啦!");
        }
        $couponDb        = new IModel('coupon');
        $couponSumResult = $couponDb->query("send_type =1 and status in(1,2,3,4,5,6) and coupon_group_id=" . $coupon_id . "  GROUP BY status ", ' status,count(*) as count');
        $goods_sale_num  = 0;
        $numArr          = array();
        if ($couponSumResult) {
            foreach ($couponSumResult as $val) {
                $goods_sale_num         += $val['count'];
                $numArr[$val['status']] = $val['count'];
            }
        }
        $coupon_info['use_type']       = $use_type;
        $coupon_info['coupon_id']      = $coupon_id;
        $coupon_info['goods_sale_num'] = $goods_sale_num;
        $coupon_info['has_send']       = $numArr[2] + $numArr[3];
        $coupon_info['remain']         = $numArr[1];
        $coupon_info['out_date']       = $numArr[4] + $numArr[5] + $numArr[6];
        $this->setRenderData($coupon_info);
        $this->redirect('update_num');
    }

    /**
     *
     * 优惠券编辑数量的时候判断
     *
     * @return bool
     */
    public function check_coupon_num()
    {
        $coupon_id = IFilter::act(IReq::get('coupon_id'), 'int');
        if (empty($coupon_id)) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '获取优惠券失败参数不完整！'
            )));
        }
        $couponDb          = new IModel('coupon');
        $couponSumResult   = $couponDb->getObj("send_type =1 and status in(1,2,3,4,5,5) and coupon_group_id=" . $coupon_id, ' count(*) as count');
        $CouponGroupsDb    = new IModel('coupon_groups');
        $couponGroupResult = $CouponGroupsDb->getObj("id=" . $coupon_id, 'goods_sale_num,end_time');
        if ($couponSumResult['count'] < $couponGroupResult['goods_sale_num']) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '优惠券正在生成，不允许修改！'
            )));
        }
        if ($couponGroupResult['end_time'] < ITime::getDateTime()) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '优惠券已经过期，不允许修改！'
            )));
        }
        die(JSON::encode(array(
            'flag' => 'success',
        )));
    }

    /**
     * 保存数量编辑数据
     *
     */
    public function save_update_num()
    {
        $coupon_id = IFilter::act(IReq::get('coupon_id'), 'int');
        $quantity  = IFilter::act(IReq::get('quantity'), 'int');
        $use_type  = IFilter::act(IReq::get('use_type'), 'int');
        if (empty($coupon_id)) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '修改失败没有获取到优惠券id'
            )));
        }
        if (empty($quantity)) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '总数量不能为空!'
            )));
        }
        $couponDb        = new IModel('coupon');
        $couponSumResult = $couponDb->query("send_type =1 and status in(1,2,3,4,5,6) and coupon_group_id=" . $coupon_id . "  GROUP BY status ", ' status,count(*) as count');
        $numArr          = array();
        $goodSaleNum     = 0;
        if ($couponSumResult) {
            foreach ($couponSumResult as $val) {
                $goodSaleNum            += $val['count'];
                $numArr[$val['status']] = $val['count'];
            }
        }
        if ($quantity < $goodSaleNum) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '总数量只可增加，不可减少!'
            )));
        }
        if ($quantity == $goodSaleNum) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '修改的总数量和当前数量相等无需修改!'
            )));

        }
        if ($quantity > $goodSaleNum) {
            $renewAddNum = $quantity - $goodSaleNum;
            //更新商品库存
            $storeNum = $quantity - $numArr['2'] - $numArr['3'] - $numArr['4'] - $numArr['5']- $numArr['6'];
            $goodDb   = new IModel('goods');
            $goodDb->setData(array('store_nums' => $storeNum));
            $goodDb->update("coupon_group_id=" . $coupon_id);
            //变更日志记录
            $couponUpdateLogDb   = new IModel('coupon_update_log');
            $couponUpdateLogData = array(
                'coupon_group_id' => $coupon_id,
                'change_sum'      => $quantity,
                'create_time'     => ITime::getDateTime()
            );
            $couponUpdateLogDb->setData($couponUpdateLogData);
            $couponUpdateLogDb->add();
            //更新主表数据
            $couponGroupsDb = new IModel('coupon_groups');
            $couponGroupsDb->setData(array(
                'goods_sale_num' => $quantity,
                'update_time'    => ITime::getDateTime(),
            ));
            $couponGroupsDb->update("id=" . $coupon_id);
            //推入优惠券生成卷号
            if ($renewAddNum) {
                $mqData = array(
                    'coupon_group_id' => $coupon_id,
                    'use_type'        => $use_type,
                    'create_time'     => ITime::getDateTime(),
                    'goods_sale_num'  => $renewAddNum,
                );
                $this->pushCouponMq($mqData);
            }

        }
        die(JSON::encode(array(
            'flag' => 'success',
        )));
    }

    /**
     * 查看优惠券数量变更记录
     *
     */
    public function coupon_change_log()
    {
        $this->layout = '';
        $coupon_id    = IFilter::act(IReq::get('coupon_id'), 'int');

        if (empty($coupon_id)) {
            die("查看优惠券变更日志出错了!");
        }
        $couponUpdateLogDb          = new IModel('coupon_update_log');
        $couponUpdateResult['info'] = $couponUpdateLogDb->query("coupon_group_id=" . $coupon_id, '', 'create_time desc');
        $this->setRenderData($couponUpdateResult);
        $this->redirect('coupon_change_log');
    }

    /**
     * 查看优惠券发放详情
     *
     */
    public function coupon_detail()
    {
        $coupon_id = IFilter::act(IReq::get('id'), 'int');
        if (empty($coupon_id)) {
            die("查看优惠券发放详情出错了!");
        }
        $page                     = IReq::get('page') ? IFilter::act(IReq::get('page'), 'int') : 1;
        $result                   = $this->coupon_detail_data($coupon_id, $page);
        $displayData['user_info'] = $result['user_info'];
        $this->setRenderData($displayData);
        $this->redirect('coupon_detail');
    }

    /**
     * 导出excel优惠券使用情况
     */
    public function coupon_detail_report()
    {
        $coupon_id = IFilter::act(IReq::get('id'), 'int');
        if (empty($coupon_id)) {
            die("优惠券导出出错了!");
        }
        $data = $this->coupon_detail_data($coupon_id);
        if ($data['coupon_info']) {
            //构建 Excel table;
            $strTable = '<table width="500" border="1">';
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="150">券编号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="150">状态</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="150">发放时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">用户名称</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="100">用户编号</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="150">使用时间</td>';
            $strTable .= '<td style="text-align:center;font-size:12px;" width="250">备注</td>';

            $strTable .= '</tr>';
            foreach ($data['coupon_info'] as $k => $val) {
                $strTable .= '<tr>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['code'] . ' </td>';
                if ($val['status'] == 1) {
                    $status = "未发放";
                } elseif ($val['status'] == 2) {
                    $status = "未使用";
                } elseif ($val['status'] == 3) {
                    $status = "已使用";
                } elseif ($val['status'] == 4) {
                    $status = "已过期";
                } elseif ($val['status'] == 5) {
                    $status = "退款中";
                } else {
                    $status = "已退款";
                }
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $status . ' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['redeem_time'] . ' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $data['user_info'][$val['user_id']]['true_name'] . ' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $data['user_info'][$val['user_id']]['username'] . ' </td>';
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['use_time'] . ' </td>';
                if ($val['order_no']) {
                    $order_no = "使用订单：{$val['order_no']} ";
                } else {
                    $order_no = '';
                }
                if ($val['receive_order_no']) {
                    $receive_order_no = "领取订单：{$val['receive_order_no']} ";
                } else {
                    $receive_order_no = '';
                }
                $strTable .= '<td style="text-align:left;font-size:12px;">' . $order_no . $receive_order_no . $val['remark'] . $val['props_source'] . ' </td>';
                $strTable .= '</tr>';
            }
            $strTable .= '</table>';
            unset($goodList);
            $reportObj = new report();
            $reportObj->setFileName('优惠券发放详情');
            $reportObj->toDownload($strTable);
            exit();
        }

    }

    /**
     * 优惠券发放详情数据查询整合
     *
     * @param $coupon_id
     * @param $page
     *
     * @return array
     */
    public function coupon_detail_data($coupon_id, $page = '')
    {
        if (empty($coupon_id)) {
            return array();
        }
        $status    = IFilter::act(IReq::get('status'), 'int');
        $order_no  = IFilter::act(IReq::get('order_no'));
        $user_type = IFilter::act(IReq::get('user_type'), 'int');
        $user_info = IFilter::act(IReq::get('user_info'));
        $code      = IFilter::act(IReq::get('code'));
        $where     = " c.coupon_group_id=$coupon_id";
        if ($status) {
            if (is_array($status)) {
                $where .= " and c.status in (" . join(",", $status) . ")";
            } else {
                $where .= " and c.status=$status";
            }
        }
        if ($order_no) {
            $where .= " and cu.order_no=$order_no or cu.receive_order_no=$order_no";
        }
        if ($code) {
            $where .= " and c.code='{$code}'";
        }
        if ($user_type && $user_info) {
            $user_id = 0;
            if ($user_type == 1) {
                $memberDB   = new IModel('member');
                $memberInfo = $memberDB->getObj("true_name='$user_info'", 'user_id');
                if (empty($memberInfo)) {
                    $user_id = 0;
                } else {
                    $user_id = $memberInfo['user_id'];
                }
            }
            if ($user_type == 2) {
                $userDB   = new IModel('user');
                $userInfo = $userDB->getObj("username like'$user_info%'", 'id');
                if (empty($userInfo)) {
                    $user_id = 0;
                } else {
                    $user_id = $userInfo['id'];
                }
            }
            $where .= " and cu.user_id=$user_id";
        }
        $couponHandle         = new IQuery('coupon as c');
        $couponHandle->order  = "sort desc,cu.redeem_time desc";
        $couponHandle->fields = "c.*,cu.*,CASE c.status  WHEN 3 THEN 6 WHEN 2 THEN 5  WHEN 5 THEN 4 WHEN 6 THEN 3  WHEN 1 THEN 2 WHEN 4 THEN 1 ELSE 0 END AS sort";
        $couponHandle->join   = "LEFT JOIN coupon_user as cu ON cu.coupon_id=c.id";
        $couponHandle->where  = $where;
        if ($page) {
            $couponHandle->page = $page;
        }
        $this->couponHandle = $couponHandle;
        $data               = $this->couponHandle->find();
        $userInfoData       = array();
        if ($data) {
            $userIdArr = array();
            foreach ($data as $val) {
                if ($val['user_id']) {
                    $userIdArr[] = $val['user_id'];
                }
            }
            if ($userIdArr) {
                $userIdStr = (join(",", array_unique($userIdArr)));
                $userDB    = new IModel('member as m,user as u ');
                $userData  = $userDB->query('m.user_id=u.id and m.user_id in (' . $userIdStr . ') ', 'm.user_id,m.true_name,u.username');

                if ($userData) {
                    foreach ($userData as $u_val) {
                        if ($u_val['username']) {
                            $userNameSplitResult = explode('@', $u_val['username']);
                            $userName            = $userNameSplitResult[0];
                            $u_val['username']   = $userName;
                        }
                        $userInfoData[$u_val['user_id']] = $u_val;
                    }
                }
            }
        }
        $return_data = array(
            'coupon_info' => $data,
            'user_info'   => $userInfoData
        );

        return $return_data;
    }

    /**
     * 强制结束窗口消息页面
     *
     */
    public function finish_message_view()
    {
        $coupon_id = IFilter::act(IReq::get('coupon_id'), 'int');
        $url       = IUrl::creatUrl("/sellercoupon/do_finish");
        echo <<<EOF
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>强制结束</title>
        </head>

        <body>
            <div style="padding: 10px;">
            若优惠券已被引用到活动或奖励中，强制结束会导致任务结束时，没有券可以发放，请谨慎操作！
                <form action="{$url}" method="post" id="coupon_finish">
                  <input type="hidden" name="coupon_id" value="{$coupon_id}">
                </form>
            </div>
        </body>
        </html>
EOF;
    }

    /**
     * 操作结束优惠券
     *
     */
    public function do_finish()
    {
        $coupon_id = IFilter::act(IReq::get('coupon_id'), 'int');
        if (empty($coupon_id)) {
            die(JSON::encode(array(
                'flag'    => 'fail',
                'message' => '强制结束失败！参数不完整'
            )));
        }

        $couponGroupsDB = new IModel('coupon_groups');
        $couponInfo     = $couponGroupsDB->getObj("id=$coupon_id");
        $couponGroupsDB->setData(array(
            'is_stop'     => 1,
            'update_time' => ITime::getDateTime()
        ));
        $couponGroupsDB->update("id=" . $coupon_id);
        if ($couponInfo['goods_sale'] == 1) {
            $couponDb = new IModel('coupon');
            $upData   = array(
                'status'      => 4,
                'update_time' => ITime::getDateTime()
            );
            $couponDb->setData($upData);
            $updateRes = $couponDb->update("status=1 and coupon_group_id=" . $coupon_id);
            if ($updateRes === false) {
                die(JSON::encode(array(
                    'flag'    => 'fail',
                    'message' => '强制结束失败！数据更新失败'
                )));
            }
            $goodsDb = new IModel('goods');
            $goodsDb->setData(array(
                'is_del'    => 2,
                'down_time' => ITime::getDateTime()
            ));
            $goodsDb->update("coupon_group_id=" . $coupon_id);

        }
        $seller_name = $this->seller['tenant_id'];
        if ($couponInfo['prop_sale'] == 1) {
            $tenantTokenResult = SystemToken::getTenantTokenList(array($seller_name));
            $token             = $tenantTokenResult['success'][$seller_name];
            if ($tenantTokenResult['failure']) {
                die(JSON::encode(array(
                    'flag'    => 'fail',
                    'message' => '强制结束失败 ，获取Token失败'
                )));
            }
            $couponPropsDb  = new IModel('coupon_props');
            $couponPropsRes = $couponPropsDb->getObj("coupon_group_id=$coupon_id");
            if ($couponPropsRes) {
                $zxlObj        = new  zxlhelper();
                $propData      = array(
                    'coupon_props_id' => $couponPropsRes['props_id'],
                    'token'           => rawurldecode($token),
                );
                $addPropResult = $zxlObj->couponDoFinish($propData);
                if ($addPropResult === false) {
                    die(JSON::encode(array(
                        'flag'    => 'fail',
                        'message' => '强制结束失败！同步关闭道具失败'
                    )));
                }
            }
        }
        //强制检索优惠券 列表情况
        $redisObj = new IRedisCache();
        //获取redis实例
        $cache = $redisObj->r('shop');
        //获取redis配置的key
        $key = $redisObj->redis_key('coupon_list');
        $cache->zRem($key, $coupon_id);
        die(JSON::encode(array(
            'flag' => 'success',
        )));


    }

    /**
     * 图片上传
     *
     */
    public function save_images()
    {

        if (isset($_FILES) && $_FILES) {
            //调用文件上传类
            $photoObj = new PhotoUpload();
            $photo    = current($photoObj->run());
            if (empty($photo)) {
                echo json_encode(array(
                    'code' => 'error'
                ));
            }
            echo json_encode(array(
                'url'  => "/" . $photo['img'],
                'code' => 'success'
            ));
        }
    }

}